require(['highcharts', 'reportCommon'], function () {
    var lineId, dateType = "02", lineName, titleStr = "";

    function lineChange(event, treeId, treeNode) {
        if (treeNode.type === 'LINE') {
            lineId = treeNode.id;
            lineName = treeNode.name;
            //标题时间
            titleStr = chartTitle(dateType);
            getLineAnaBehIdx(lineId, dateType);
            getLineBehRankInfo(lineId, dateType);
            getLineUnBehRankInfo(lineId, dateType);
        } else {
            $.messager.alert("提示", "请选择线路进行查看。");
        }
    }

    //左侧树
    commonFun.leftTreeNodeClickObj['lineAnaBehaviorInfo'] = lineChange;

    //顶部日期类型
    $(".time-select a").click(function () {
        if (lineId) {
            dateType = $(this).attr('val');
            //标题时间
            titleStr = chartTitle(dateType);
            $(this).addClass("active");
            $(this).siblings().removeClass("active");
            getLineAnaBehIdx(lineId, dateType);
            getLineBehRankInfo(lineId, dateType);
            getLineUnBehRankInfo(lineId, dateType);
        }
    });

    //行为数据
    function getLineAnaBehIdx(lineId, dateType) {
        $.ajaxExt({
            url: "/lineAna/getLineAnaBehIdx.htm",
            data: {'lineId': lineId, 'dateType': dateType}
        }).done(function (data) {
            //每日故障数据
            var series = [], category = [],
                tmpDate = data[0].REPORT_DATE;
            for (var i = 0; i < data.length; i++) {
                if (data[i].REPORT_DATE == tmpDate) {
                    series.push({"name": data[i].TREND_VAL1, data: []});
                } else {
                    break;
                }
            }
            for (i = 0; i < data.length; i += series.length) {
                xAxisDateFormat(dateType, category, data[i].REPORT_DATE);
                for (var s = 0; s < series.length; s++) {
                    series[s].data.push(parseInt(data[i + s].TREND_VAL2));
                }
            }
            $('#lineBehData').highcharts({
                chart: {
                    type: 'column'
                },
                title: {
                    text: "线路：" + lineName + ' ' + titleStr,
                    style: {
                        fontFamily: 'sans-serif',
                        fontSize: '14px'
                    }
                },
                xAxis: {
                    categories: category
                },
                yAxis: {
                    title: {
                        text: '次数'
                    },
                    stackLabels: {
                        enabled: true,
                        style: {
                            fontWeight: 'bold',
                            color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                        }
                    }
                },
                credits: {
                    enabled: false
                },
                legend: {
                    align: 'center',
                    verticalAlign: 'bottom',
                    y: 20,
                    floating: true,
                    backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
                    borderColor: '#CCC',
                    shadow: false
                },
                tooltip: {
                    formatter: function () {
                        return '<b>' + this.x + '</b><br/>' +
                            this.series.name + ': ' + this.y + '<br/>' +
                            'Total: ' + this.point.stackTotal;
                    }
                },
                plotOptions: {
                    column: {
                        stacking: 'normal',
                    }
                },
                series: series
            });
        });
    }

    //行为排名 饼图
    function getLineBehRankInfo(lineId, dateType) {
        $.ajaxExt({
            url: "/lineAna/getLineBehRankInfo.htm",
            data: {'lineId': lineId, 'dateType': dateType}
        }).done(function (data) {
            var behaviorPct = [],
                trHtml = "<tr><th width='15%'>排名</th><th width='25%'>行为名称</th><th width='15%'>次数</th><th width='20%'>百分比</th></tr>";
            $(data).each(function (i, item) {
                if (item.IDX_TYPE == "050701") {
                    if (item.RANK_SN <= 5) {
                        //行为排名 填充数据
                        trHtml += "<tr><td><span class='rank-tip'>" + item.RANK_SN + "</span></td><td>" + item.RANK_VAL1 + "</td><td>" + item.RANK_VAL2 + "</td><td>" + item.RANK_VAL3 + "</td></tr>";
                    }
                    //百分比图 填充数据
                    behaviorPct.push([item.RANK_VAL1, parseInt(item.RANK_VAL3) || 0]);
                }
            });
            $("#trHtml").html(trHtml);
            //百分比图
            $("#unBehPct").highcharts({
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false
                },
                title: {
                    text: "线路：" + lineName + ' ' + titleStr,
                    style: {
                        fontFamily: 'sans-serif',
                        fontSize: '14px'
                    }
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            color: '#000000',
                            connectorColor: '#000000',
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                        }
                    }
                },
                credits: {
                    enabled: false
                },
                series: [
                    {
                        type: 'pie',
                        name: '不文明行为比例',
                        data: behaviorPct
                    }
                ]
            });
        });
    }

    //不良驾驶行为排名
    function getLineUnBehRankInfo(lineId, dateType) {
        $.ajaxExt({
            url: "/lineAna/getLineUnBehRankInfo.htm",
            data: {'lineId': lineId, 'dateType': dateType}
        }).done(function (data) {
            var series = [], lic = [], lx = [], category = [], lxArr = [];
            var tmpVal = [];//, tmpLic = [];
            $(data).each(function (i, item) {
                lic.push(item.LIC_PLT_NO);
                lx.push(item.RANK_VAL1);
                if(category.length == 0 || category.indexOf(item.LIC_PLT_NO) < 0){
                	category.push(item.LIC_PLT_NO);
                	tmpVal.push(parseInt(item.RANK_VAL3));
                }else{
                	var num = category.indexOf(item.LIC_PLT_NO);
                	tmpVal[num] += parseInt(item.RANK_VAL3);
                }
            });
            //类别根据总数排名
            for(var i=0;i<tmpVal.length;i++){
            	for(var j=i+1;j<tmpVal.length;j++){
            		if(tmpVal[i] < tmpVal[j]){
            			var tmp = tmpVal[j];
            			tmpVal[j] = tmpVal[i];
            			tmpVal[i] = tmp;
            			
            			tmp = category[j];
            			category[j] = category[i];
            			category[i] = tmp;
            			
            		}
            	}
            }
            lxArr.push(lx[0]);
            
            for(var i=1;i<lx.length;i++){
            	if(lxArr.indexOf(lx[i]) < 0){
            		lxArr.push(lx[i]);
            	}
            }
            for (var i = 0; i < lxArr.length; i++) {
                var tmp = [];
                for (var j = 0; j < category.length; j++) {
                    tmp.push(parseInt(0));
                }
                series.push({"name": lxArr[i], data: tmp});
            }
            for (var k = 0; k < lxArr.length; k++) {//类型
                for (var i = 0; i < category.length; i++) {//25 车
                    for (var j = 0; j < data.length; j++) {//42 数据
                        if (category[i] == data[j].LIC_PLT_NO && lxArr[k] == data[j].RANK_VAL1) {
                            series[k].data[i] = parseInt(data[j].RANK_VAL3);
                        }
                    }
                }
            }
            
            console.info(series);
            
            // 不良驾驶行为排名
            $('#unBehRank').highcharts({
                chart: {
                    type: 'bar'
                },
                title: {
                    text: "线路：" + lineName + ' ' + titleStr,
                    style: {
                        fontFamily: 'sans-serif',
                        fontSize: '14px'
                    }
                },
                credits: {
                    enabled: false
                },
                xAxis: {
                    categories: category
                },
                yAxis: {
                    title: {
                        text: ''
                    }
                },
                legend: {
                    backgroundColor: '#FFFFFF',
                    reversed: true
                },
                plotOptions: {
                    series: {
                        stacking: 'normal'
                    }
                },
                series: series
            });
        });

    }

    //如果左侧树有选择车辆则直接查询该车辆数据
    business.execFnByLeftTreeSelectNode('LINE', lineChange);
});